package com.yilin.tms.core.commons.zysdk;

import org.apache.http.HttpStatus;

import javax.net.ssl.*;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpsUtils {
    public HttpsUtils() {
    }
    //
    public static String doPost(String url, int connentTimeout, int readTimeout) throws Exception {
        HttpURLConnection conn = null;
        InputStreamReader isReader = null;
        StringBuffer result = new StringBuffer();

        try {
            trustAllHttpsCertificates();
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
            conn = (HttpURLConnection)(new URL(url)).openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(connentTimeout);
            conn.setReadTimeout(readTimeout);
            isReader = new InputStreamReader(conn.getInputStream(), "UTF-8");
            char[] bfchar = new char[2048];
            boolean var8 = false;

            int length;
            while((length = isReader.read(bfchar)) != -1) {
                String temp = new String(bfchar, 0, length);
                result.append(temp);
            }
        } catch (Exception var17) {
            System.err.println("发送 POST 请求出现异常！" + var17.getMessage());
            throw var17;
        } finally {
            try {
                if (isReader != null) {
                    isReader.close();
                }
            } catch (IOException var16) {
                System.err.println("关闭数据流出错了！\n" + var16.getMessage() + "\n");
                throw var16;
            }

        }

        return result.toString();
    }

    public static String doPost(String url, String param, int readTimeout, int connectTimeout) throws Exception {
        InputStreamReader isReader = null;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        StringBuffer result = new StringBuffer();

        try {
            trustAllHttpsCertificates();
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
            conn = (HttpURLConnection)(new URL(url)).openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            conn.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
            conn.setRequestProperty("Accept","*/*");
            conn.setRequestProperty("Content-Length", String.valueOf(param.getBytes("UTF-8").length));
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(connectTimeout);
            conn.setRequestProperty("charset", "UTF-8");
            conn.setReadTimeout(readTimeout);
            conn.connect();
            dos = new DataOutputStream(conn.getOutputStream());
            int length = 0;
            int totalLength = param.length();

            while(length < totalLength) {
                int endLength = length + 1024;
                if (endLength > totalLength) {
                    endLength = totalLength;
                }
                dos.write(param.substring(length, endLength).getBytes("UTF-8"));
                length = endLength;
                dos.flush();
            }
            InputStream is = null;
            int status = conn.getResponseCode();
            if(status>= HttpStatus.SC_BAD_REQUEST){  //此处一定要根据返回的状态码state来初始化输入流。如果为错误
                is = conn.getErrorStream();
            }else{
                is = conn.getInputStream();
            }
            dos.close();
            isReader = new InputStreamReader(is, "UTF-8");
            char[] bfchar = new char[2048];
            boolean var12 = false;

            int rlength;
            while((rlength = isReader.read(bfchar)) != -1) {
                String temp = new String(bfchar, 0, rlength);
                result.append(temp);
            }

            return result.toString();
        } catch (Exception var21) {
            System.err.println("发送 POST 请求出现异常！" + var21.getMessage() + "e:" + var21);
            throw var21;
        } finally {
            try {
                if (isReader != null) {
                    isReader.close();
                }
            } catch (IOException var20) {
                System.err.println("关闭数据流出错了！\n" + var20.getMessage() + "\n");
                throw var20;
            }

        }
    }

    private static void trustAllHttpsCertificates() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init((KeyManager[])null, trustAllCerts, (SecureRandom)null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    static class miTM implements TrustManager, X509TrustManager {
        miTM() {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }
    }
}
